<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--客户类别数据-->
        <pane size="15" min-size="10">
          <el-col>
            <div class="head-container">
              <el-input v-model="categoryName" placeholder="请输入类别名称" clearable size="small" prefix-icon="el-icon-search"
                style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="categoryOptions" :props="defaultProps" :expand-on-click-node="false"
                :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--客户数据-->
        <pane size="85">
          <el-col :span="24">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="客户名称" prop="customerName">
                <el-input
                  v-model="queryParams.customerName"
                  placeholder="请输入客户名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <!-- <el-form-item label="客户分类ID" prop="customerCategoryId">
                <el-input
                  v-model="queryParams.customerCategoryId"
                  placeholder="请输入客户分类ID"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="价格等级" prop="priceLevel">
                <el-input
                  v-model="queryParams.priceLevel"
                  placeholder="请输入价格等级"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="专属折扣" prop="exclusiveDiscount">
                <el-input
                  v-model="queryParams.exclusiveDiscount"
                  placeholder="请输入专属折扣"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="初始积分" prop="initialPoints">
                <el-input
                  v-model="queryParams.initialPoints"
                  placeholder="请输入初始积分"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="初始欠款" prop="initialDebt">
                <el-input
                  v-model="queryParams.initialDebt"
                  placeholder="请输入初始欠款"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="联系人" prop="contactPerson">
                <el-input
                  v-model="queryParams.contactPerson"
                  placeholder="请输入联系人"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item> -->
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input
                  v-model="queryParams.contactPhone"
                  placeholder="请输入联系电话"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <!-- <el-form-item label="联系地址" prop="contactAddress">
                <el-input
                  v-model="queryParams.contactAddress"
                  placeholder="请输入联系地址"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="收货地址" prop="shippingAddress">
                <el-input
                  v-model="queryParams.shippingAddress"
                  placeholder="请输入收货地址"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="收货人" prop="consignee">
                <el-input
                  v-model="queryParams.consignee"
                  placeholder="请输入收货人"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="收货人电话" prop="consigneePhone">
                <el-input
                  v-model="queryParams.consigneePhone"
                  placeholder="请输入收货人电话"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="是否为默认收货地址" prop="defaultShippingAddress">
                <el-input
                  v-model="queryParams.defaultShippingAddress"
                  placeholder="请输入是否为默认收货地址"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="是否使用客户联系地址" prop="useContactAddress">
                <el-input
                  v-model="queryParams.useContactAddress"
                  placeholder="请输入是否使用客户联系地址"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item> -->
              <!-- <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="queryParams.email"
                  placeholder="请输入邮箱"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item> -->
              <!-- <el-form-item label="传真" prop="fax">
                <el-input
                  v-model="queryParams.fax"
                  placeholder="请输入传真"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="开户银行" prop="bankName">
                <el-input
                  v-model="queryParams.bankName"
                  placeholder="请输入开户银行"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="银行账号" prop="bankAccount">
                <el-input
                  v-model="queryParams.bankAccount"
                  placeholder="请输入银行账号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="生日" prop="birthday">
                <el-date-picker clearable
                  v-model="queryParams.birthday"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择生日">
                </el-date-picker>
              </el-form-item> -->
              <el-form-item label="微信号" prop="wechatId">
                <el-input
                  v-model="queryParams.wechatId"
                  placeholder="请输入微信号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <!-- <el-form-item label="QQ" prop="qq">
                <el-input
                  v-model="queryParams.qq"
                  placeholder="请输入QQ"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['customer:customer:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['customer:customer:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['customer:customer:remove']"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['customer:customer:export']"
                >导出</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange" 
              style="width: 100%" :max-height="tableHeight">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="自增长主键" align="center" prop="id" />
              <el-table-column label="客户名称" align="center" prop="customerName" />
              <el-table-column label="客户分类ID" align="center" prop="customerCategoryId" />
              <el-table-column label="价格等级" align="center" prop="priceLevel" />
              <el-table-column label="专属折扣" align="center" prop="exclusiveDiscount" />
              <el-table-column label="初始积分" align="center" prop="initialPoints" />
              <el-table-column label="初始欠款" align="center" prop="initialDebt" />
              <el-table-column label="联系人" align="center" prop="contactPerson" />
              <el-table-column label="联系电话" align="center" prop="contactPhone" />
              <el-table-column label="联系地址" align="center" prop="contactAddress" />
              <el-table-column label="收货地址" align="center" prop="shippingAddress" />
              <el-table-column label="收货人" align="center" prop="consignee" />
              <el-table-column label="收货人电话" align="center" prop="consigneePhone" />
              <el-table-column label="是否为默认收货地址" align="center" prop="defaultShippingAddress" />
              <el-table-column label="是否使用客户联系地址" align="center" prop="useContactAddress" />
              <el-table-column label="邮箱" align="center" prop="email" />
              <el-table-column label="传真" align="center" prop="fax" />
              <el-table-column label="开户银行" align="center" prop="bankName" />
              <el-table-column label="银行账号" align="center" prop="bankAccount" />
              <el-table-column label="生日" align="center" prop="birthday" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="微信号" align="center" prop="wechatId" />
              <el-table-column label="QQ" align="center" prop="qq" />
              <el-table-column label="备注" align="center" prop="remark" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['customer:customer:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['customer:customer:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="customer-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户分类" prop="customerCategoryId">
          <treeselect 
            v-model="form.customerCategoryId" 
            :options="categoryOptions" 
            :normalizer="normalizer"
            :show-count="true" 
            placeholder="请选择客户分类" />
        </el-form-item>
        <el-form-item label="价格等级" prop="priceLevel">
          <el-input v-model="form.priceLevel" placeholder="请输入价格等级" />
        </el-form-item>
        <el-form-item label="专属折扣" prop="exclusiveDiscount">
          <el-input v-model="form.exclusiveDiscount" placeholder="请输入专属折扣" />
        </el-form-item>
        <el-form-item label="初始积分" prop="initialPoints">
          <el-input v-model="form.initialPoints" placeholder="请输入初始积分" />
        </el-form-item>
        <el-form-item label="初始欠款" prop="initialDebt">
          <el-input v-model="form.initialDebt" placeholder="请输入初始欠款" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系地址" prop="contactAddress">
          <el-input v-model="form.contactAddress" placeholder="请输入联系地址" />
        </el-form-item>
        <el-form-item label="收货地址" prop="shippingAddress">
          <el-input v-model="form.shippingAddress" placeholder="请输入收货地址" />
        </el-form-item>
        <el-form-item label="收货人" prop="consignee">
          <el-input v-model="form.consignee" placeholder="请输入收货人" />
        </el-form-item>
        <el-form-item label="收货人电话" prop="consigneePhone">
          <el-input v-model="form.consigneePhone" placeholder="请输入收货人电话" />
        </el-form-item>
        <el-form-item label="是否为默认收货地址" prop="defaultShippingAddress">
          <el-input v-model="form.defaultShippingAddress" placeholder="请输入是否为默认收货地址" />
        </el-form-item>
        <el-form-item label="是否使用客户联系地址" prop="useContactAddress">
          <el-input v-model="form.useContactAddress" placeholder="请输入是否使用客户联系地址" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="传真" prop="fax">
          <el-input v-model="form.fax" placeholder="请输入传真" />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker clearable
            v-model="form.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="微信号" prop="wechatId">
          <el-input v-model="form.wechatId" placeholder="请输入微信号" />
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="form.qq" placeholder="请输入QQ" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/business/customer";
import { listCategory } from "@/api/business/customerCategory";
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Customer",
  components: { Splitpanes, Pane, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCustomerCategory: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 客户分类表格数据
      customerCategoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        customerCategoryId: null,
        priceLevel: null,
        exclusiveDiscount: null,
        initialPoints: null,
        initialDebt: null,
        contactPerson: null,
        contactPhone: null,
        contactAddress: null,
        shippingAddress: null,
        consignee: null,
        consigneePhone: null,
        defaultShippingAddress: null,
        useContactAddress: null,
        email: null,
        fax: null,
        bankName: null,
        bankAccount: null,
        birthday: null,
        wechatId: null,
        qq: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
      },
      // 新增的数据
      // 客户类别名称
      categoryName: "",
      // 客户类别树选项
      categoryOptions: [],
      // 客户类别树配置
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      // 添加表格高度变量
      tableHeight: 400,
    };
  },
  watch: {
    // 根据名称筛选客户类别树
    categoryName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getCategoryTree(); // 获取客户类别树
    this.calculateTableHeight(); // 计算表格高度
  },
  mounted() {
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeDestroy() {
    // 移除监听器
    window.removeEventListener('resize', this.calculateTableHeight);
  },
  methods: {
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customerName: null,
        customerCategoryId: null,
        priceLevel: null,
        exclusiveDiscount: null,
        initialPoints: null,
        initialDebt: null,
        contactPerson: null,
        contactPhone: null,
        contactAddress: null,
        shippingAddress: null,
        consignee: null,
        consigneePhone: null,
        defaultShippingAddress: null,
        useContactAddress: null,
        email: null,
        fax: null,
        bankName: null,
        bankAccount: null,
        birthday: null,
        wechatId: null,
        qq: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.customerCategoryList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.customerCategoryId = undefined; // 重置类别ID
      this.$refs.tree && this.$refs.tree.setCurrentKey(null); // 清除树选中状态
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryTree(); // 确保在打开表单前获取最新的类别树
      this.open = true;
      this.title = "添加客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getCategoryTree(); // 确保在打开表单前获取最新的类别树
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data;
        this.customerCategoryList = response.data.customerCategoryList || [];
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.customerCategoryList = this.customerCategoryList;
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户编号为"' + ids + '"的数据项？').then(function() {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 查询客户类别树结构 */
    getCategoryTree() {
      listCategory().then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.customerCategoryId = data.id;
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('customer/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    },
    // 添加计算表格高度的方法
    calculateTableHeight() {
      this.$nextTick(() => {
        const windowHeight = window.innerHeight;
        // 减去其他元素的高度，如页头、搜索表单、分页等
        this.tableHeight = windowHeight - 265; 
      });
    },
    /** 转换客户类别数据结构 */
    normalizer(node) {
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
  }
};
</script>

<style scoped>
.customer-dialog /deep/ .el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
  padding: 10px;
}

.app-container{
  padding: 15px;
}

/* 修改分割面板相关样式 */
.splitpanes {
  height: calc(100vh - 120px);
}

.head-container {
  padding: 0 10px;
}

/* 树节点样式 */
.el-tree-node__content {
  height: 32px;
}

.el-tree-node.is-current > .el-tree-node__content {
  background-color: #f0f7ff;
  color: #409EFF;
}

/* 添加表格容器样式 */
.el-table {
  width: 100%;
  overflow-x: auto;
}

/* 确保右侧面板内容不溢出 */
.splitpanes__pane {
  overflow: hidden;
}

/* 添加树形选择器样式 */
.vue-treeselect {
  width: 100%;
}
</style>
å